<?php
declare(strict_types=1);

namespace ExpressionEngine\LexicalAnalysisEngine;

use ExpressionEngine\LexicalAnalysisEngine\Loop\LexicalAnalysisLoopInterface;
use ExpressionEngine\LoopEngine\Enum\LoopEnum;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\ContainerInterface;
use Psr\Container\NotFoundExceptionInterface;

class LexicalAnalysisLoop
{
    protected ContainerInterface $container;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    /**
     * @param string $expression
     * @return array
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function scan(string &$expression): array
    {
        $loopList = [];
        foreach (LoopEnum::LEXICAL_ANALYSIS_LOOP_LIST as $lexicalAnalysisLoopClass) {
            /** @var LexicalAnalysisLoopInterface $lexicalAnalysisLoopInstance */
            $lexicalAnalysisLoopInstance = $this->container->get($lexicalAnalysisLoopClass);
            if ($lexicalAnalysisLoopInstance->is($expression)) {
                $lexicalAnalysisLoopInstance->validate($expression);
                $loopList = $lexicalAnalysisLoopInstance->scan($expression, $loopList);
                break;
            }
        }
        return $loopList;
    }
}